<template>
  <div class="bg-white">
    <div class="px-[20px]">
      <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
        <!-- <el-tab-pane label="基础设置" name="first">
          <el-alert
            title=" 开启前，请先配置通道（如拉卡拉）信息；开启后，该商家标记为聚合支付类型商家！关闭后，则取消标记！"
            type="warning"
          />
          <vxe-form
            v-if="isFinish"
            ref="firstFormRef"
            v-bind="baseFormOptions"
            v-on="formEvents"
          />
        </el-tab-pane> -->
        <el-tab-pane label="拉卡拉" name="second">
          <vxe-form v-if="isFinish" ref="secondFormRef" v-bind="lklFormOptions" v-on="lklFormEvents" />
        </el-tab-pane>
        <el-tab-pane label="汇付支付" name="third">
          <vxe-form v-if="isFinish" ref="thirdFormRef" v-bind="hfFormOptions" v-on="hfFormEvents" />
        </el-tab-pane>
      </el-tabs>
    </div>
    <!-- <el-affix z-index="4" position="bottom">
      <div class="w-full flex justify-center bg-white py-[20px] shadow-2xl">
        <el-button type="primary" @click="handleSubmit">保存</el-button>
        <el-button @click="$router.back()">返回</el-button>
      </div>
    </el-affix> -->
  </div>
</template>
<script lang="ts" setup>
import { ref } from "vue";
import type { TabsPaneContext } from "element-plus";
import PaymentAPI, {
  PaymentLklSettingVO,
  PaymentSettingVO,
} from "@/api/payment";
import { VxeFormListeners, VxeFormProps } from "vxe-pc-ui";
import { Dict, useDict } from "@/composes/useDict";

const PAY_TYPE = [
  { label: "微信", value: "WECHAT" },
  { label: "支付宝", value: "ALIPAY" },
];

const FZ_TYPE = [
  { label: "订单分账", value: "TR" },
  { label: "余额分账", value: "BA" },
];

const setBaseItems = (data: any[]) => {
  baseFormOptions.items = [
    {
      field: "status",
      title: "聚合支付",
      span: 24,
      itemRender: {
        name: "ElSwitch",
        props: { activeValue: 1, inactiveValue: 0 },
      },
    },
    ...data,
    {
      field: "isShow",
      title: "是否显示分账",
      span: 24,
      itemRender: {
        name: "ElSwitch",
        props: { activeValue: 1, inactiveValue: 0 },
      },
    },
    {
      align: "center",
      span: 24,
      itemRender: {
        name: "VxeButtonGroup",
        options: [
          { type: "submit", content: "保存", status: "primary" },
          { content: "返回", "router-link": { name: "StoreIndex" } },
        ],
      },
    },
  ];
};

const activeName = ref("second");
const baseFormOptions = reactive<VxeFormProps<PaymentSettingVO>>({
  titleColon: true,
  titleWidth: 200,
  titleAlign: "right",
  className: "vxe-form-fixed",
  data: {},
  items: [],
});
const lklFormOptions = reactive<VxeFormProps<PaymentLklSettingVO>>({
  titleColon: true,
  titleWidth: 200,
  titleAlign: "right",
  className: "vxe-form-fixed",
  data: {},
  rules: {
    appid: [{ required: true, message: "请输入名称" }],
    serial_no: [{ required: true, message: "请输入证书序列号" }],
    publicKey: [{ required: true, message: "请输入公钥证书文件" }],
    merchantId: [{ required: true, message: "请输入私钥证书文件" }],
    merCupNo: [{ required: true, message: "请输入银联商家号" }],
    term_no: [{ required: true, message: "请输入B2B收银台-扫码终端号" }],
    // vposId: [{ required: true, message: "请输入B2B收银台-终端号" }],
    // sm4Key: [{ required: true, message: "请输入国密4(SM4Key)" }],
    payType: [{ required: true, message: "请选择支付类型" }],
    term_profession_no: [{ required: true, message: "请输入平台机构代码" }],
  },
  items: [],
});

const formEvents: VxeFormListeners<PaymentSettingVO> = {
  submit({ data }) {
    if (!data.channelType) {
      ElMessage.error("通道不能为空");
      return false;
    }

    const { id } = data;
    const submitData = { ...data, storeCode: route.query.storeCode as string };
    submitData.payType = (submitData?.payType as [string])?.join(",");
    // submitData.separateType = (submitData?.separateType as [string])?.join(",");

    if (id) {
      PaymentAPI.updateSetting(submitData).then((res) => {
        ElMessage.success("修改成功");
      });
    } else {
      PaymentAPI.addSetting(submitData).then((res) => {
        ElMessage.success("添加成功");
      });
    }
  },
};
const lklFormEvents: VxeFormListeners<PaymentLklSettingVO> = {
  submit({ data }) {
    const { id } = data;
    const submitData = {
      ...data,
      storeCode: route.query.storeCode as string,
      channelType: 1,
    };
    alert(submitData.payType)
    submitData.payType = (submitData?.payType as [string])?.join(",");
    alert(submitData.separateType)
    if (submitData.separateType) {
      submitData.separateType = (submitData?.separateType as [string])?.join(",");
    }


    if (id) {
      PaymentAPI.updateLklSetting(submitData).then((res) => {
        ElMessage.success("修改成功");
      });
    } else {
      PaymentAPI.addLklSetting(submitData).then((res) => {
        ElMessage.success("添加成功");
      });
    }
  },
};

const hfFormOptions = reactive<VxeFormProps<PaymentLklSettingVO>>({
  titleColon: true,
  titleWidth: 200,
  titleAlign: "right",
  className: "vxe-form-fixed",
  data: {},
  rules: {
    systemId: [{ required: true, message: "请输入系统号" }],
    productId: [{ required: true, message: "请输入产品" }],
    serial_no: [{ required: true, message: "请输入证书序列号" }],
    publicKey: [{ required: true, message: "请输入公钥证书文件" }],
    serialKey: [{ required: true, message: "请输入私钥证书文件" }],
    merCupNo: [{ required: true, message: "请输入银联商家号" }],
    term_no: [{ required: true, message: "请输入B2B收银台-扫码终端号" }],
    // vposId: [{ required: true, message: "请输入B2B收银台-终端号" }],
    // sm4Key: [{ required: true, message: "请输入国密4(SM4Key)" }],
    payType: [{ required: true, message: "请选择支付类型" }],
    term_profession_no: [{ required: true, message: "请输入平台机构代码" }],
  },
  items: [],
});

const hfFormEvents: VxeFormListeners<PaymentLklSettingVO> = {
  submit({ data }) {
    console.log(data);
    const { id } = data;
    const submitData = {
      ...data,
      storeCode: route.query.storeCode as string,
      channelType: 2,
    };
    submitData.payType = (submitData?.payType as [string])?.join(",");
    if (submitData.separateType) {
      submitData.separateType = (submitData?.separateType as [string])?.join(",");
    }


    if (id) {
      PaymentAPI.updateLklSetting(submitData).then((res) => {
        ElMessage.success("修改成功");
      });
    } else {
      PaymentAPI.addLklSetting(submitData).then((res) => {
        ElMessage.success("添加成功");
      });
    }
  },
};

const handleClick = (tab: TabsPaneContext, event: Event) => {
  console.log(tab, channelType.value);
  if (channelType.value === 1 && tab.paneName === "third") {
    hfFormOptions.data = {};
  }
  if (channelType.value === 2 && tab.paneName === "second") {
    lklFormOptions.data = {};
  }
};

const isFinish = ref(false);
const settingDetail = ref();

const firstFormRef = ref();
const secondFormRef = ref();

const route = useRoute();

const handleSubmit = () => {
  if (activeName.value === "first") {
    firstFormRef.value?.dispatchEvent("submit");
  } else {
    secondFormRef.value?.dispatchEvent("submit");
  }
};

const initFormConfig = (dicts: Dict) => {
  console.log(settingDetail.value?.id);
  const arr = settingDetail.value?.id
    ? []
    : [
      {
        field: "userName",
        title: "用户账号",
        span: 24,
        itemRender: { name: "ElInput" },
      },
      {
        field: "password",
        title: "密码",
        span: 24,
        itemRender: { name: "ElInput" },
      },
    ];
  lklFormOptions.items = [
    // {
    //   field: "status",
    //   title: "拉卡拉",
    //   span: 24,
    //   itemRender: {
    //     name: "ElSwitch",
    //     props: { activeValue: 1, inactiveValue: 0 },
    //   },
    // },
    // {
    //   field: "keyType",
    //   title: "请求密钥类型",
    //   span: 24,
    //   itemRender: {
    //     name: "ElRadioGroup",
    //     attrs: {
    //       tips: "商家支付、分账请求的密钥类型，大部分情况下需要商家独立密钥， 请根据通道要求选择，如果是渠道统一密钥，请在聚合支付插件中设置统一密钥！",
    //     },
    //     options: [
    //       { label: "商家独立密钥", value: 1 },
    //       { label: "渠道统一密钥", value: 2 },
    //     ],
    //   },
    // },
    {
      field: "appid",
      title: "接入方唯一编号(appid)",
      span: 24,
      itemRender: { name: "ElInput" },
    },
    {
      field: "serialNo",
      title: "证书序列号(serial_no)",
      span: 24,
      itemRender: { name: "ElInput" },
    },
    {
      field: "publicKey",
      title: "公钥证书文件",
      span: 24,
      itemRender: { name: "ElInput", props: { type: "textarea" } },
    },
    {
      field: "serialKey",
      title: "私钥证书文件",
      span: 24,
      itemRender: { name: "ElInput", props: { type: "textarea" } },
    },
    {
      field: "merCupNo",
      title: "银联商家号(merCupNo)",
      span: 24,
      itemRender: { name: "ElInput" },
    },
    {
      field: "merchantNo",
      title: "商家号(merchant_no)",
      span: 24,
      itemRender: { name: "ElInput" },
    },
    {
      field: "termNo",
      title: "B2B收银台-扫码终端号(term_no)",
      span: 24,
      itemRender: { name: "ElInput" },
    },
    {
      field: "termCardNo",
      title: "B2B收银台-银行卡终端号(term_card_no)",
      span: 24,
      itemRender: { name: "ElInput" },
    },
    {
      field: "termProfessionNo",
      title: "专业化扫码支付终端号(term_profession_no)",
      span: 24,
      itemRender: { name: "ElInput" },
    },
    // {
    //   field: "vposId",
    //   title: "vpos_id",
    //   span: 24,
    //   itemRender: { name: "ElInput" },
    // },
    // {
    //   field: "sm4Key",
    //   title: "国密4(SM4Key)",
    //   span: 24,
    //   itemRender: { name: "ElInput" },
    // },
    {
      field: "payType",
      title: "支付类型",
      span: 24,
      itemRender: {
        name: "ElCheckboxGroup",
        options: dicts.allPaTypesList,
      },
    },
    {
      field: "cashType",
      title: "拉卡拉收银台下单接口",
      span: 24,
      itemRender: {
        name: "ElRadioGroup",
        options: [
          { label: "新接口", value: 0 },
          { label: "旧接口", value: 1 },
        ],
      },
    },
    {
      field: "separateType",
      title: "分账类型",
      span: 24,
      itemRender: {
        name: "ElCheckboxGroup",
        options: FZ_TYPE,
      },
    },
    {
      field: "orgCode",
      title: "平台机构代码",
      span: 24,
      itemRender: { name: "ElInput" },
    },
    {
      field: "urlAddress",
      title: "回调地址",
      span: 24,
      itemRender: { name: "ElInput" },
    },
    ...arr,
    {
      align: "center",
      span: 24,
      itemRender: {
        name: "VxeButtonGroup",
        options: [
          { type: "submit", content: "保存", status: "primary" },
          { content: "返回", "router-link": { name: "StoreIndex" } },
        ],
      },
    },
  ];
  hfFormOptions.items = [
    // {
    //   field: "status",
    //   title: "汇付支付",
    //   span: 24,
    //   itemRender: {
    //     name: "ElSwitch",
    //     props: { activeValue: 1, inactiveValue: 0 },
    //   },
    // },
    {
      field: "systemId",
      title: "系统号",
      span: 24,
      itemRender: { name: "ElInput" },
    },
    {
      field: "productId",
      title: "产品号",
      span: 24,
      itemRender: { name: "ElInput" },
    },
    {
      field: "publicKey",
      title: "公钥证书文件",
      span: 24,
      itemRender: { name: "ElInput", props: { type: "textarea" } },
    },
    {
      field: "serialKey",
      title: "私钥证书文件",
      span: 24,
      itemRender: { name: "ElInput", props: { type: "textarea" } },
    },
    {
      field: "merCupNo",
      title: "商户号",
      span: 24,
      itemRender: { name: "ElInput" },
    },
    {
      field: "payType",
      title: "支付类型",
      span: 24,
      itemRender: {
        name: "ElCheckboxGroup",
        options: dicts.allPaTypesList,
      },
    },
    {
      field: "separateType",
      title: "分账类型",
      span: 24,
      itemRender: {
        name: "ElCheckboxGroup",
        options: FZ_TYPE,
      },
    },
    {
      field: "settlementCycle",
      title: "结算周期",
      span: 24,
      itemRender: {
        name: "ElSelect",
        options: dicts.settleTypesList,
      },
    },
    {
      field: "receiverNo",
      title: "平台机构代码",
      span: 24,
      itemRender: { name: "ElInput" },
    },
    ...arr,
    {
      align: "center",
      span: 24,
      itemRender: {
        name: "VxeButtonGroup",
        options: [
          { type: "submit", content: "保存", status: "primary" },
          { content: "返回", "router-link": { name: "StoreIndex" } },
        ],
      },
    },
  ];
};

const channelType = ref();

const { storeCode } = route.query;
useDict((dicts: Dict) => {
  Promise.all([
    PaymentAPI.getLklSettingDetail(storeCode as string),
    PaymentAPI.getSettingDetail(storeCode as string),
  ])
    .then(([lklRef, baseRef]) => {
      if (!lklRef?.msg) {
        settingDetail.value = lklRef;
        initFormConfig(dicts);
        channelType.value = lklRef.channelType;
        if (channelType.value === 1) {
          activeName.value = "second";
          lklFormOptions.data = { ...lklRef };
          if (lklRef?.payType) {
            lklFormOptions.data.payType = lklRef?.payType?.split(",") ?? [];
          }
          if (lklRef?.separateType) {
            lklFormOptions.data.separateType =
              (lklRef.separateType as string)?.split(",") ?? [];
          }
        } else {
          activeName.value = "third";
          hfFormOptions.data = { ...lklRef };

          if (lklRef?.payType) {
            hfFormOptions.data.payType = lklRef?.payType?.split(",") ?? [];
          }
          if (lklRef?.separateType) {
            hfFormOptions.data.separateType =
              (lklRef?.separateType as string)?.split(",") ?? [];
          }
        }

        // if (baseRef?.channelType) {
        //   if (baseRef?.channelType === 1) {
        //     lklFormOptions.data.status = 1;
        //     hfFormOptions.data.status = 0;
        //   } else if (baseRef.channelType === 2) {
        //     hfFormOptions.data.status = 1;
        //     lklFormOptions.data.status = 0;
        //   }
        // }
        setBaseItems([
          {
            field: "channelType",
            title: "通道",
            span: 24,
            itemRender: {
              name: "ElRadioGroup",
              options: [
                { label: "拉卡拉", value: 1 },
                { label: "汇付支付", value: 2 },
              ],
            },
          },
          {
            field: "payType",
            title: "支付类型",
            span: 24,
            itemRender: {
              props: {
                disabled: false,
              },
              name: "ElCheckboxGroup",
              options: dicts.allPaTypesList,
            },
          },
          {
            field: "separateType",
            title: "分账类型",
            span: 24,
            itemRender: {
              props: {
                disabled: false,
              },
              name: "ElRadioGroup",
              options: FZ_TYPE,
            },
          },
        ]);
      } else {
        setBaseItems([
          {
            field: "channelType",
            title: "通道",
            span: 24,
            itemRender: {
              name: "VxeTips",
              props: {
                content: "该商户不存在进件完成通道",
              },
            },
          },
        ]);
      }
      // if (!baseRef?.msg) {
      //   baseFormOptions.data = baseRef;
      //   if (lklRef?.payType) {
      //     baseFormOptions.data.payType =
      //       (baseRef.payType as string)?.split(",") ?? [];
      //   }
      //   // baseFormOptions.data.separateType =
      //   //   (baseRef.separateType as string)?.split(",") ?? [];
      // }
      // if (lklFormOptions.data) {
      //   if (!baseFormOptions.data) {
      //     baseFormOptions.data = {};
      //   }
      //   baseFormOptions.data.payType = lklFormOptions.data.payType;
      //   baseFormOptions.data.separateType = lklFormOptions.data.separateType;
      // }
    })
    .finally(() => {
      isFinish.value = true;
    });
});
</script>

<style>
.demo-tabs>.el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}
</style>
